
import redis from 'redis';
import bluebird from 'bluebird';



export function InitRedis({ host, post, auth, db = 0 }) {
    //将所有操作都变成promiss
    //如get,调用就是getAsync
    bluebird.promisifyAll(redis.RedisClient.prototype);
    bluebird.promisifyAll(redis.Multi.prototype);

    const client = redis.createClient({
        host,
        post,
        db,
    });
    client.auth(auth, (call) => {
        //  console.log("auth:" + call);
    });
    client.on("error", function (err) {
        console.log("Error " + err);
    });


    return client;
}

function setString(client, key, value) {
    return client.setAsync(key, value).then(function (res) {
        return res === 1;
    });
}

function getString(client, key) {
    return client.getAsync(key).then(function (res) {
        return res;
    });
}

function delString(client, key) {
    return client.delAsync(key).then(function (res) {
        return res === 1;
    });
}

function setHashValue(client, key, hkey, hvalue) {
    return client.hsetAsync(key, hkey, hvalue).then(function (res) {
        return res === 1;
    });
}

function getHashValue(client, key, hkey) {
    return client.hgetAsync(key, hkey).then(function (res) {
        return res;
    });
}

function getHashValueAll(client, key) {
    return client.hgetallAsync(key).then(function (res) {
        return res;
    });
}

function delHashValue(client, key, hkey) {
    return client.hdelAsync(key, hkey).then(function (res) {
        return res === 1;
    });
}
export default { setString, getString, delString, setHashValue, getHashValue, getHashValueAll, delHashValue }